/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package interfaceGrafica;

import analisadorSemantico.AnalisadorSemantico;
import analisadorSintatico.AnalisadorSintatico;
import analisadorSintatico.NoInterno;
import analisadorlexico.AnalisadorLexico;
import java.awt.Color;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;
import javax.swing.text.Element;
import modelo.Constante;
import modelo.Funcao;
import modelo.Procedimento;
import modelo.Programa;
import modelo.Simbolo;
import modelo.TipoIdentificador;
import modelo.Token;
import modelo.Variavel;
import modelo.tipos.TipoVariavel;

/**
 *
 * @author DEP
 */
public class AnalisadorUI extends javax.swing.JFrame {

    private JFileChooser fc;
    private char[] caracteres = null;
    private List<Token> tokens;
    private File arquivo = null;
    private AnalisadorLexico analisadorLexico;
    private AnalisadorSintatico analisadorSintatico;
    private NoInterno raiz;
    private JTextArea lines;

    public AnalisadorUI() {
        initComponents();
        lines = new JTextArea("1");
        lines.setBackground(Color.CYAN);
        lines.setEditable(false);
        lines.setFont(txtCodigoFonte.getFont());
        txtCodigoFonte.getDocument().addDocumentListener(new DocumentListener() {
            public String getText() {
                int caretPosition = txtCodigoFonte.getDocument().getLength();
                Element root = txtCodigoFonte.getDocument().getDefaultRootElement();
                String text = "1" + System.getProperty("line.separator");
                for (int i = 2; i < root.getElementIndex(caretPosition) + 2; i++) {
                    text += i + System.getProperty("line.separator");
                }
                return text;
            }

            @Override
            public void changedUpdate(DocumentEvent de) {
                lines.setText(getText());
            }

            @Override
            public void insertUpdate(DocumentEvent de) {
                lines.setText(getText());
            }

            @Override
            public void removeUpdate(DocumentEvent de) {
                lines.setText(getText());
            }
        });
        jScrollPane4.setRowHeaderView(lines);

        this.setLocationRelativeTo(null);
        analisadorLexico = new AnalisadorLexico();
        this.setTitle("Analizador Lexico-Sintático-Semântico");
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jFrame1 = new javax.swing.JFrame();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTree1 = new javax.swing.JTree();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jScrollPane7 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        btnAnalisar = new javax.swing.JButton();
        jScrollPane4 = new javax.swing.JScrollPane();
        txtCodigoFonte = new javax.swing.JTextArea();
        btnLimpar = new javax.swing.JButton();
        btnFechar = new javax.swing.JButton();
        btnArvore = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jTabbedPane2 = new javax.swing.JTabbedPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtErroLexico = new javax.swing.JTextArea();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane5 = new javax.swing.JScrollPane();
        txtErroSintatico = new javax.swing.JTextArea();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane6 = new javax.swing.JScrollPane();
        txtErroSemantico = new javax.swing.JTextArea();
        jTabbedPane3 = new javax.swing.JTabbedPane();
        jScrollPane2 = new javax.swing.JScrollPane();
        tblTokens = new javax.swing.JTable();
        jScrollPane8 = new javax.swing.JScrollPane();
        tblSimbolo = new javax.swing.JTable();
        jMenuBar1 = new javax.swing.JMenuBar();
        mnuArquivo = new javax.swing.JMenu();
        mnuAbrir = new javax.swing.JMenuItem();
        mnuSair = new javax.swing.JMenuItem();

        javax.swing.GroupLayout jFrame1Layout = new javax.swing.GroupLayout(jFrame1.getContentPane());
        jFrame1.getContentPane().setLayout(jFrame1Layout);
        jFrame1Layout.setHorizontalGroup(
            jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        jFrame1Layout.setVerticalGroup(
            jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        jScrollPane3.setViewportView(jTree1);

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane7.setViewportView(jTable1);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        btnAnalisar.setText("Analisar");
        btnAnalisar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAnalisarActionPerformed(evt);
            }
        });

        txtCodigoFonte.setColumns(20);
        txtCodigoFonte.setRows(5);
        txtCodigoFonte.setBorder(null);
        jScrollPane4.setViewportView(txtCodigoFonte);

        btnLimpar.setText("Limpar");
        btnLimpar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLimparActionPerformed(evt);
            }
        });

        btnFechar.setText("Fechar");
        btnFechar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnFecharActionPerformed(evt);
            }
        });

        btnArvore.setText("Visualizar Árvore");
        btnArvore.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnArvoreActionPerformed(evt);
            }
        });

        jLabel1.setText("Código Fonte");

        txtErroLexico.setColumns(20);
        txtErroLexico.setRows(5);
        txtErroLexico.setBorder(null);
        jScrollPane1.setViewportView(txtErroLexico);

        jTabbedPane2.addTab("Erro Léxico", jScrollPane1);

        txtErroSintatico.setColumns(20);
        txtErroSintatico.setRows(5);
        jScrollPane5.setViewportView(txtErroSintatico);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane5, javax.swing.GroupLayout.DEFAULT_SIZE, 393, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane5, javax.swing.GroupLayout.DEFAULT_SIZE, 141, Short.MAX_VALUE)
        );

        jTabbedPane2.addTab("Erro Sintático", jPanel1);

        txtErroSemantico.setColumns(20);
        txtErroSemantico.setRows(5);
        jScrollPane6.setViewportView(txtErroSemantico);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jScrollPane6, javax.swing.GroupLayout.DEFAULT_SIZE, 393, Short.MAX_VALUE)
                .addGap(0, 0, 0))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane6, javax.swing.GroupLayout.DEFAULT_SIZE, 141, Short.MAX_VALUE)
        );

        jTabbedPane2.addTab("Erro Semântico", jPanel2);

        tblTokens.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Linha", "Token", "Tipo"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane2.setViewportView(tblTokens);

        jTabbedPane3.addTab("Tokens", jScrollPane2);

        tblSimbolo.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Linha", "ID", "Tipo ID", "Valor ID", "Escopo", "Parâmetros"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane8.setViewportView(tblSimbolo);

        jTabbedPane3.addTab("Tabela de Símbolos", jScrollPane8);

        mnuArquivo.setText("Arquivo");

        mnuAbrir.setText("Abrir txt");
        mnuAbrir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuAbrirActionPerformed(evt);
            }
        });
        mnuArquivo.add(mnuAbrir);

        mnuSair.setText("Sair");
        mnuSair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuSairActionPerformed(evt);
            }
        });
        mnuArquivo.add(mnuSair);

        jMenuBar1.add(mnuArquivo);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 319, Short.MAX_VALUE)
                        .addGap(18, 18, 18))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnLimpar)
                        .addGap(34, 34, 34)
                        .addComponent(btnAnalisar)
                        .addGap(18, 18, 18)
                        .addComponent(btnArvore)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnFechar))
                    .addComponent(jTabbedPane2)
                    .addComponent(jTabbedPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane4))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jTabbedPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 278, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jTabbedPane2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(btnAnalisar)
                            .addComponent(btnLimpar)
                            .addComponent(btnFechar)
                            .addComponent(btnArvore))))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void mnuSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuSairActionPerformed
        System.exit(0);
    }//GEN-LAST:event_mnuSairActionPerformed

    private void mnuAbrirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuAbrirActionPerformed
        try {
            AbrirArquivo();
        } catch (FileNotFoundException ex) {
            JOptionPane.showMessageDialog(this, "Arquivo não encontrado.");
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(this, "Erro ao abrir arquivo.");
        }
    }//GEN-LAST:event_mnuAbrirActionPerformed

    private void btnAnalisarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAnalisarActionPerformed
        //lexico
        limparErros();
        limparTabelaTokens();
        analisadorLexico.setCodigoFonte(txtCodigoFonte.getText());
        analisadorLexico.analisar();
        tokens = analisadorLexico.getTokens();
        InserirTabelaToken(tokens);
        txtErroLexico.setText(analisadorLexico.getErros());

        //sintatico
        analisadorSintatico = new AnalisadorSintatico(tokens);
        analisadorSintatico.analisar();
        raiz = analisadorSintatico.getRaiz();
        txtErroSintatico.setText(analisadorSintatico.getErrosSintaticos());


        //semantico
        analisadorLexico.setCodigoFonte(txtCodigoFonte.getText());
        analisadorLexico.analisar();
        tokens = analisadorLexico.getTokens();
        AnalisadorSemantico analisadorSemantico = new AnalisadorSemantico(tokens,raiz);
        analisadorSemantico.analisar();
        txtErroSemantico.setText(analisadorSemantico.getErrosSemanticos());
        InserirTabelaSimbolo(analisadorSemantico.getTabelaSimbolos());
    }//GEN-LAST:event_btnAnalisarActionPerformed

    private void btnLimparActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLimparActionPerformed
        limparCodigoFonte();
        limparErros();
        limparTabelaTokens();
    }//GEN-LAST:event_btnLimparActionPerformed

    private void btnFecharActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFecharActionPerformed
        System.exit(0);
    }//GEN-LAST:event_btnFecharActionPerformed

    private void btnArvoreActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnArvoreActionPerformed
        if (raiz == null) {
            JOptionPane.showMessageDialog(this, "Faça a análise primeiro.");
        } else {
            Arvore arv = new Arvore(this, true, raiz.getNo());
            arv.setLocationRelativeTo(this);
            arv.setVisible(true);
        }
    }//GEN-LAST:event_btnArvoreActionPerformed

    public void AbrirArquivo() throws FileNotFoundException, IOException {
        fc = new JFileChooser();
        fc.setFileFilter(new FileNameExtensionFilter("Arquivos de texto (*.txt)", "txt"));

        String linha, nome;
        int tam = 0;
        int resultado = fc.showOpenDialog(this);

        if (resultado == JFileChooser.APPROVE_OPTION) {
            txtCodigoFonte.setText("");
            arquivo = fc.getSelectedFile();
            nome = arquivo.getName();
            tam = (int) nome.length();

            FileReader ler = new FileReader(arquivo);
            BufferedReader leitor = new BufferedReader(ler);

            while ((linha = leitor.readLine()) != null) {
                txtCodigoFonte.append(linha + "\n");
                txtCodigoFonte.setCaretPosition(txtCodigoFonte.getText().length());
            }

            leitor.close();
            ler.close();
        } else {
            JOptionPane.showMessageDialog(this, "Nenhum arquivo selecionado", "Ops!", JOptionPane.INFORMATION_MESSAGE);
        }
    }

    private void limparErros() {
        txtErroLexico.setText("");
    }

    private void limparCodigoFonte() {
        txtCodigoFonte.setText("");
    }

    private void limparTabelaTokens() {
        while (tblTokens.getRowCount() > 0) {
            ((DefaultTableModel) tblTokens.getModel()).removeRow(0);
        }
    }

    private void limparTabelaSimbolos() {
        while (tblSimbolo.getRowCount() > 0) {
            ((DefaultTableModel) tblSimbolo.getModel()).removeRow(0);
        }
    }

    public void InserirTabelaSimbolo(List<Simbolo> simbolos) {
        DefaultTableModel model = (javax.swing.table.DefaultTableModel) tblSimbolo.getModel();

        limparTabelaSimbolos();


        for (Simbolo s : simbolos) {
            if (s != null) {

                TipoIdentificador ti = s.getTipo();
                if (ti instanceof Funcao) {
                    model.addRow(new Object[]{ti.getLinha(), s.getNome(), "Funçao", ((Funcao) ti).getRetorno(), ti.getEscopo(), obterParametros(((Funcao) ti).getParametros())});
                } else if (ti instanceof Procedimento) {
                    model.addRow(new Object[]{ti.getLinha(), s.getNome(), "Procedimento", "-", ti.getEscopo(), obterParametros(((Procedimento) ti).getParametros())});
                } else if (ti instanceof Programa) {
                    model.addRow(new Object[]{ti.getLinha(), s.getNome(), "Programa", "-", ti.getEscopo(), "-"});
                } else if (ti instanceof Constante) {
                    model.addRow(new Object[]{ti.getLinha(), s.getNome(), "Constante", ti.getTipo(), ti.getEscopo(), "-"});
                } else if (ti instanceof Variavel) {
                    model.addRow(new Object[]{ti.getLinha(), s.getNome(), "Variável", ti.getTipo(), ti.getEscopo(), "-"});
                }
            }
        }

    }

    private String obterParametros(Map<String, TipoVariavel> parametros) {
        String resultado = "";
        if (parametros != null && !parametros.isEmpty()) {
            Set<String> chaves = parametros.keySet();
            for (String chave : chaves) {
                resultado += parametros.get(chave) + ",";
            }

            return (resultado.substring(0, resultado.length() - 1));
        }
        return "-";


    }

    public void InserirTabelaToken(List<Token> list) {
        Token token;
        DefaultTableModel model = (javax.swing.table.DefaultTableModel) tblTokens.getModel();

        while (tblTokens.getRowCount() > 0) {
            model.removeRow(0);
        }

        for (int i = 0; i < list.size(); i++) {
            token = list.get(i);
            model.addRow(new Object[]{token.getLinha(), token.getToken(), token.getTipo()});
        }

    }

    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Windows".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(AnalisadorUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(AnalisadorUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(AnalisadorUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AnalisadorUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new AnalisadorUI().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAnalisar;
    private javax.swing.JButton btnArvore;
    private javax.swing.JButton btnFechar;
    private javax.swing.JButton btnLimpar;
    private javax.swing.JFrame jFrame1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JScrollPane jScrollPane5;
    private javax.swing.JScrollPane jScrollPane6;
    private javax.swing.JScrollPane jScrollPane7;
    private javax.swing.JScrollPane jScrollPane8;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JTabbedPane jTabbedPane2;
    private javax.swing.JTabbedPane jTabbedPane3;
    private javax.swing.JTable jTable1;
    private javax.swing.JTree jTree1;
    private javax.swing.JMenuItem mnuAbrir;
    private javax.swing.JMenu mnuArquivo;
    private javax.swing.JMenuItem mnuSair;
    private javax.swing.JTable tblSimbolo;
    private javax.swing.JTable tblTokens;
    private javax.swing.JTextArea txtCodigoFonte;
    private javax.swing.JTextArea txtErroLexico;
    private javax.swing.JTextArea txtErroSemantico;
    private javax.swing.JTextArea txtErroSintatico;
    // End of variables declaration//GEN-END:variables
}
